﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MM.Common.Setup;
using System.ComponentModel;
using MM.Common.UI.Controls;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraNavBar;
using DevExpress.XtraGrid;
using MM.Common.DBBase;
using MM.Common.Base;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using System.Data;
using System.IO;
using DevExpress.XtraEditors.Repository;
using System.Drawing;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Utils;
using System.Drawing.Drawing2D;
using System.Diagnostics;

namespace MM.Common.Information
{
    public partial class FrmFileIssue : FrmSetupWithItem
    {
        protected PDFFactory _Pdf;
        protected NavBarItem nbiQuery;

        public FrmFileIssue()
        {
            this.InitializeComponent();
            this.AddBarItem();
            this._Pdf = new PDFFactory();
            base.gvItem = this.gvRole;
            base.gvList = this.gvFile;
        }

        private void AddBarItem()
        {
            this.nbiQuery = new NavBarItem();
            this.nbiQuery.Caption = "查询";
            this.nbiQuery.Hint = "查询文件内容";
            this.nbiQuery.Name = "nbiQuery";
            this.nbiQuery.Enabled = true;
            this.nbiQuery.LinkClicked += new NavBarLinkEventHandler(this.nbiQuery_LinkClicked);
            base.navBarControl1.Items.Add(this.nbiQuery);
            base.nbgFunction.ItemLinks.Insert(3, this.nbiQuery);
        }

        protected override void afterInsert()
        {
            this.txtFileCode.Text = "";
            this.txtFileTitle.Text = "";
            base.dtItem.Rows.Clear();
        }

        private void cbFileType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SetDefaultCode();
        }

        protected override void changeMode(bool edit)
        {
            base.changeMode(edit);
            base.pgBase.Enabled = true;
            this.cbFileType.Properties.ReadOnly = !base.isEdit;
            this.txtFileCode.Properties.ReadOnly = !base.isEdit;
            this.txtFileTitle.Properties.ReadOnly = !base.isEdit;
        }

        protected override void deleteRecord()
        {
            if (XtraMessageBox.Show("是否真的删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string paramValue = base.gvList.GetFocusedRowCellValue("FILE_CODE").ToString();
                string[] commandtexts = new string[2];
                DataParamCol[] parms = new DataParamCol[2];
                commandtexts[0] = "DELETE FROM KTSYS_FILE_ROLE WHERE FILE_CODE = :fcode";
                parms[0] = new DataParamCol(new DataParam[] { new InputDataParam("fcode", paramValue) });
                commandtexts[1] = "DELETE FROM KTSYS_FILE WHERE FILE_CODE = :fcode";
                parms[1] = new DataParamCol(new DataParam[] { new InputDataParam("fcode", paramValue) });
                if (SystemInfo.DbData.RunSql(commandtexts, parms) == 0)
                {
                    base.gvList.DeleteRow(base.gvList.FocusedRowHandle);
                    base.gvList.Focus();
                }
            }
        }
        protected override void freshDisp()
        {
            DataRow focusedDataRow = this.gvFile.GetFocusedDataRow();
            if (focusedDataRow != null)
            {
                this.txtFileCode.Text = focusedDataRow["FILE_CODE"].ToString();
                this.txtFileTitle.Text = focusedDataRow["FILE_TITLE"].ToString();
                this.cbFileType.EditValue = focusedDataRow["FILE_TYPE_CODE"].ToString();
                base.dtItem.Rows.Clear();
                base.dtItem.AcceptChanges();
                DataParamCol parm = new DataParamCol();
                parm.Add(new InputDataParam("code", focusedDataRow["FILE_CODE"].ToString()));
                SystemInfo.DbData.Retrieve("SELECT R.ROLE_CODE ,R.ROLE_NAME FROM KTSYS_FILE_ROLE F ,KTSYS_ROLE R WHERE F.ROLE_CODE = R.ROLE_CODE AND F.FILE_CODE = :code", parm, ref this.dtItem);
                base.dtItem.PrimaryKey = new DataColumn[] { base.dtItem.Columns["ROLE_CODE"] };
            }
            this._Pdf.FileName = "";
        }

        private void FrmFileIssue_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                Directory.Delete(SystemInfo.RunPath + "Temp", true);
            }
            catch
            {
            }
        }

        protected override void getChoiceItem()
        {
            int[] numArray = new int[2];
            numArray[1] = 100;
            new FrmMulSelFromGrid(base.dtItemAll, new string[] { "代码", "名称" }, numArray, "文件角色选择", ref this.dtItem).ShowDialog(this);
        }

        protected override void getItemAll()
        {
            base.dtItemAll.Clear();
            SystemInfo.DbData.Retrieve("SELECT ROLE_CODE ,ROLE_NAME FROM KTSYS_ROLE ORDER BY ROLE_CODE", ref this.dtItemAll);
            base.dtItemAll.PrimaryKey = new DataColumn[] { base.dtItemAll.Columns["ROLE_CODE"] };
        }

        public override bool Init()
        {
            bool flag = false;
            if (base.Init())
            {
                DataTable dt = new DataTable();
                SystemInfo.DbData.Retrieve("SELECT * FROM KTSYS_FILE_TYPE ORDER BY FILE_TYPE_CODE", ref dt);
                this.cbFileType.Properties.DataSource = dt;
                this.cbFileType.Properties.DisplayMember = "FILE_TYPE_NAME";
                this.cbFileType.Properties.ValueMember = "FILE_TYPE_CODE";
                base.gvItem.GridControl.DataSource = base.dtItem;
                base.dtList = new DataTable();
                DataParamCol parm = new DataParamCol();
                parm.Add(new InputDataParam("id", SystemInfo.OperId));
                SystemInfo.DbData.Retrieve("SELECT FILE_CODE ,FILE_TYPE_CODE ,FILE_TITLE FROM KTSYS_FILE WHERE ISSUE_EMP_ID = :id ORDER BY FILE_CODE", parm, ref this.dtList);
                base.dtList.TableName = "KTSYS_FILE";
                base.nbiChoice.Caption = "角色";
                base.InitData();
                flag = true;
            }
            return flag;
        }

        private void nbiQuery_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if (base.isEdit)
            {
                OpenFileDialog dialog = new OpenFileDialog
                {
                    Title = "选择内容文件",
                    InitialDirectory = SystemInfo.RunPath + @"Content\",
                    Filter = "PDF文件(*.pdf)|*.pdf",
                    FilterIndex = 1,
                    RestoreDirectory = true
                };
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    this._Pdf.FileName = dialog.FileName;
                    if (this.txtFileTitle.Text == "")
                    {
                        int num = dialog.FileName.LastIndexOf(@"\");
                        string str = dialog.FileName.Substring(num + 1);
                        this.txtFileTitle.Text = str.Substring(0, str.Length - 4);
                    }
                    if (XtraMessageBox.Show("是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Process.Start(dialog.FileName);
                    }
                }
            }
            else if (this.gvFile.FocusedRowHandle >= 0)
            {
                string filecode = this.gvFile.GetFocusedRowCellValue("FILE_CODE").ToString();
                this._Pdf.CreatePdf(filecode);
                Process.Start(this._Pdf.FileName);
            }
        }

        protected override bool saveRecord()
        {
            string[] strArray;
            DataParamCol[] colArray;
            bool flag = true;
            int rowCount = this.gvRole.RowCount;
            string text = this.txtFileCode.Text;
            string paramValue = "";
            if (base.isNew)
            {
                strArray = new string[rowCount + 1];
                colArray = new DataParamCol[rowCount + 1];
            }
            else
            {
                strArray = new string[rowCount + 2];
                colArray = new DataParamCol[rowCount + 2];
            }
            if (base.isNew)
            {
                strArray[0] = "INSERT INTO KTSYS_FILE (FILE_CODE ,FILE_TITLE ,FILE_TYPE_CODE ,ISSUE_EMP_ID) VALUES (:code ,:title ,:tcode ,:emp_id)";
                DataParamCol col = new DataParamCol();
                col.Add(new InputDataParam("code", text));
                col.Add(new InputDataParam("title", this.txtFileTitle.Text));
                col.Add(new InputDataParam("tcode", this.cbFileType.EditValue));
                col.Add(new InputDataParam("emp_id", SystemInfo.OperId));
                colArray[0] = col;
            }
            else
            {
                paramValue = this.gvFile.GetFocusedRowCellValue("FILE_CODE").ToString();
                strArray[0] = "UPDATE KTSYS_FILE SET FILE_CODE = :code ,FILE_TITLE = :title ,FILE_TYPE_CODE = :tcode ,ISSUE_EMP_ID = :emp_id, ISSUE_TIME = SYSDATE WHERE FILE_CODE = :ocode";
                DataParamCol col2 = new DataParamCol();
                col2.Add(new InputDataParam("code", text));
                col2.Add(new InputDataParam("title", this.txtFileTitle.Text));
                col2.Add(new InputDataParam("tcode", this.cbFileType.EditValue));
                col2.Add(new InputDataParam("emp_id", SystemInfo.OperId));
                col2.Add(new InputDataParam("ocode", paramValue));
                colArray[0] = col2;
            }
            int index = 1;
            if (!base.isNew)
            {
                strArray[1] = "DELETE FROM KTSYS_FILE_ROLE WHERE FILE_CODE = :ocode";
                DataParamCol col3 = new DataParamCol();
                col3.Add(new InputDataParam("ocode", paramValue));
                colArray[1] = col3;
                index++;
            }
            for (int i = 0; i < this.gvRole.RowCount; i++)
            {
                strArray[index] = "INSERT INTO KTSYS_FILE_ROLE (FILE_CODE ,ROLE_CODE) VALUES (:fcode ,:rcode) ";
                DataParamCol col4 = new DataParamCol();
                col4.Add(new InputDataParam("fcode", text));
                col4.Add(new InputDataParam("rcode", this.gvRole.GetRowCellValue(i, "ROLE_CODE").ToString()));
                colArray[index] = col4;
                index++;
            }
            SystemInfo.DbData.TransactionBegin();
            if (SystemInfo.DbData.RunSql(strArray, colArray) == 0)
            {
                if (this._Pdf.SavePdf(text))
                {
                    SystemInfo.DbData.TransactionCommit();
                    if (base.isNew)
                    {
                        DataRow row = base.dtList.NewRow();
                        row["FILE_CODE"] = this.txtFileCode.Text;
                        row["FILE_TITLE"] = this.txtFileTitle.Text;
                        row["FILE_TYPE_CODE"] = this.cbFileType.EditValue;
                        base.dtList.Rows.Add(row);
                        this.gvFile.FocusedRowHandle = this.gvFile.RowCount - 1;
                        return flag;
                    }
                    this.gvFile.SetFocusedRowCellValue("FILE_CODE", text);
                    this.gvFile.SetFocusedRowCellValue("FILE_TITLE", this.txtFileTitle.Text);
                    this.gvFile.SetFocusedRowCellValue("FILE_TYPE_CODE", this.cbFileType.EditValue);
                    return flag;
                }
                SystemInfo.DbData.TransactionRollback();
                flag = false;
                XtraMessageBox.Show("文件内容加入不成功！\r\n" + SystemInfo.DbData.ErrorMessage);
                return flag;
            }
            SystemInfo.DbData.TransactionRollback();
            flag = false;
            XtraMessageBox.Show("数据加入不成功！\r\n" + SystemInfo.DbData.ErrorMessage);
            return flag;
        }

        protected void SetDefaultCode()
        {
            if (base.isNew)
            {
                string paramValue = this.cbFileType.GetColumnValue("FILE_TYPE_CODE").ToString();
                string data = "";
                DataParamCol parms = new DataParamCol();
                parms.Add(new InputDataParam("tcode", paramValue));
                SystemInfo.DbData.ExecuteScalar<string>("SELECT MAX(FILE_CODE) FROM KTSYS_FILE WHERE FILE_TYPE_CODE = :tcode", parms, ref data);
                string str3 = paramValue + "001";
                if (data != "")
                {
                    str3 = (Convert.ToInt16(data) + 1).ToString("00000");
                }
                this.txtFileCode.Text = str3;
            }
        }
    }
}
